package com.jhw.ymcc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jhw.ymcc.constants.GrowScoreConstants;
import com.jhw.ymcc.domain.UserBaseInfo;
import com.jhw.ymcc.domain.UserGrowLog;
import com.jhw.ymcc.mapper.UserBaseInfoMapper;
import com.jhw.ymcc.service.IUserBaseInfoService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 会员基本信息 服务实现类
 * </p>
 *
 * @author jhw
 * @since 2022-09-23
 */
@Service
public class UserBaseInfoServiceImpl extends ServiceImpl<UserBaseInfoMapper, UserBaseInfo> implements IUserBaseInfoService {

    @Override
    public void growScoreFromRegister(Long userId) {
        // 添加成长值表
        saveUserBaseInfo(userId, GrowScoreConstants.GROW_SCORE_REFER_REGISTER);
        // 添加成长值日志表
        saveUserBaseInfoLog(userId,GrowScoreConstants.GROW_SCORE_FROM_REGISTER,GrowScoreConstants.GROW_SCORE_REFER_REGISTER);
    }

    /**
     * 保存成长值日志表
     * @param userId 用户id
     * @param from 成长值来源
     */
    private void saveUserBaseInfoLog(Long userId,String from, Integer growScore) {
        UserGrowLog userGrowLog = new UserGrowLog();
        userGrowLog.setCreateTime(System.currentTimeMillis());
        userGrowLog.setUserId(userId);
        userGrowLog.setFromReason(from);
        userGrowLog.setScore(growScore);
    }

    /**
     * 保存成长值表
     * @param userId
     * @param growScore
     */
    private void saveUserBaseInfo(Long userId, Integer growScore) {
        UserBaseInfo userBaseInfo = selectOne(new EntityWrapper<UserBaseInfo>().eq("id", userId));
        if (userBaseInfo != null) {
            int growScore1 = userBaseInfo.getGrowScore() + growScore;
            userBaseInfo.setGrowScore(userBaseInfo.getGrowScore() + growScore);
            userBaseInfo.setLevel(getLevel(growScore1));
            super.updateById(userBaseInfo);
        }

    }

    public Integer getLevel(Integer growScore) {
        if (growScore >= 0 && growScore<=99) {
            return GrowScoreConstants.LEVEL_BRONZE;
        } else if (growScore >= 100 && growScore<=299) {
            return GrowScoreConstants.LEVEL_SILVER;
        } else if (growScore >= 300 && growScore<=599) {
            return GrowScoreConstants.LEVEL_GOLD;
        } else if (growScore >= 600 && growScore<=999) {
            return GrowScoreConstants.LEVEL_PLATINUM;
        } else if (growScore >= 1000 && growScore<1499) {
            return GrowScoreConstants.LEVEL_DIAMONDS;
        } else if (growScore >= 1500 && growScore<=2499) {
            return GrowScoreConstants.LEVEL_MASTER;
        } else {
            return GrowScoreConstants.LEVEL_KING;
        }
    }

}
